<template>
  <div class="office-preview-container">
    <div class="office-controls">
      <el-button
        type="primary"
        size="mini"
        @click="downloadOriginal"
        icon="el-icon-download"
      >
        下载原始文件
      </el-button>

      <el-tooltip :content="isFullscreen ? '退出全屏' : '全屏'" placement="top">
        <el-button
          :icon="isFullscreen ? 'el-icon-close' : 'el-icon-full-screen'"
          @click="$emit('toggle-fullscreen')"
        />
      </el-tooltip>
    </div>

    <div class="preview-wrapper">
      <iframe
        :src="src"
        class="office-iframe"
        frameborder="0"
        @load="handleLoad"
        @error="handleError"
      ></iframe>

      <div v-if="loading" class="loading-overlay">
        <i class="el-icon-loading" />
        正在加载Office文档...
      </div>

      <div v-if="error" class="error-overlay">
        <i class="el-icon-document" />
        <p>文档加载失败</p>
        <el-button type="primary" size="mini" @click="retry">
          重试
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    src: {
      type: String,
      required: true
    },
    isFullscreen: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: true,
      error: false
    }
  },
  methods: {
    handleLoad() {
      this.loading = false
      this.error = false
    },
    handleError() {
      this.loading = false
      this.error = true
    },
    retry() {
      this.loading = true
      this.error = false
      this.$forceUpdate() // 强制刷新iframe
    },
    downloadOriginal() {
      const link = document.createElement('a')
      link.href = this.src.replace('embed.aspx', 'view.aspx')
      link.target = '_blank'
      link.click()
    }
  }
}
</script>

<style scoped>
.office-preview-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.office-controls {
  padding: 10px;
  background: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.preview-wrapper {
  flex: 1;
  position: relative;
}

.office-iframe {
  width: 100%;
  height: 100%;
  border: none;
}

.loading-overlay,
.error-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #606266;
}

.error-overlay p {
  margin: 10px 0;
}
</style>
